﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mesoBoard.Data.Repositories;
using mesoBoard.Data;
using System.Text.RegularExpressions;
using System.Xml;
using System.Text;
using mesoBoard.Common;
using mesoBoard.Common.UrlHelpers;

namespace mesoBoard.Common.HtmlHelpers
{
    public static partial class mesoBoardHtmlHelpers
    {
        public static string SyntaxHighlightingScripts(this HtmlHelper html, params SyntaxHighlighting[] langs)
        {
            UrlHelper Url = new UrlHelper(html.ViewContext.RequestContext);

            StringBuilder str = new StringBuilder();

            string javascript = "<script language='javascript' src='{0}' />";
            string style = string.Format("<link type='text/css' rel='stylesheet' href='{0}' />", Url.ThemeContent("Content/SyntaxHighlighter/Styles/SyntaxHighlighter.css"));

            str.AppendLine(style);
            str.AppendLine(string.Format(javascript, Url.ThemeContent("Content/SyntaxHighlighter/Scripts/shCore.js")));
            
            foreach (var l in langs)
            {
                string url = string.Format(Url.ThemeContent("Content/SyntaxHighlighter/Scripts/shBrush{0}.js"), l.ToString());
                str.AppendLine(string.Format(javascript, url));
            }

            TagBuilder runScript = new TagBuilder("script");
            runScript.Attributes.Add("language", "javascript");
            runScript.InnerHtml = string.Format("dp.SyntaxHighlighter.ClipboardSwf = '{0}';{1}dp.SyntaxHighlighter.HighlightAll('code');",
                Url.ThemeContent("Content/SyntaxHighlighter/Scripts/clipboard.swf"), Environment.NewLine);

            str.AppendLine(runScript.ToString());

            return str.ToString();
        }

        public static string SyntaxHighlightingScripts(this HtmlHelper html, string commaDelimitedList)
        {
            string[] split = commaDelimitedList.Split(',');

            List<SyntaxHighlighting> langs = new List<SyntaxHighlighting>();

            foreach (string s in split)
            {
                langs.Add((SyntaxHighlighting)Enum.Parse(typeof(SyntaxHighlighting), s));
            }

            return SyntaxHighlightingScripts(html, langs.ToArray());

        }

        public static decimal PercentOfVotes(this HtmlHelper html, int voteCount, int totalVotes)
        {
            if (totalVotes == 0)
                return 0;

            decimal ratio = (decimal)voteCount / (decimal)totalVotes;
            decimal percent = ratio * 100;

            return Math.Round(percent);
        }

        public static string VoteBar(this HtmlHelper html, int voteCount, int totalVotes)
        {
            TagBuilder tag = new TagBuilder("div");
            tag.AddCssClass("vote_bar");

            tag.InnerHtml = "&nbsp;";
            decimal percent = PercentOfVotes(html, voteCount, totalVotes) / 2;
            tag.Attributes.Add("style", "width:" + percent .ToString() + "%");
            return tag.ToString();
        }

        public static string ParsePostText(this HtmlHelper html, string PostText)
        {
            UrlHelper Url = new UrlHelper(html.ViewContext.RequestContext);
            RepositoriesWrapper Repositories = new RepositoriesWrapper(new mbEntities());

            IEnumerable<BBCode> BBCodes = Repositories.BBCodes.GetBBCodes();
            string ParsedText = "";
            ParsedText = PostText.Replace(Environment.NewLine, "<br />");

            MatchCollection code = Regex.Matches(ParsedText, @"\[code=\b([^\]]*)\](.*?)\[/code\]", RegexOptions.Singleline);

            foreach (Match codematch in code)
            {
                if (codematch.Success)
                {
                    string matchcode = codematch.Value.Replace("<br />", Environment.NewLine);
                    ParsedText = ParsedText.Replace(codematch.Value, matchcode);
                }
            }

            foreach (BBCode b in BBCodes)
            {
                string Pat = b.Pattern;

                Regex Reg = new Regex(Pat, RegexOptions.Singleline);

                MatchCollection matches = Reg.Matches(ParsedText);

                if (matches.Count > 0)
                {
                    for (int j = 0; j < matches.Count; j++)
                    {
                        Match m = matches[j];
                        string evaled = b.Parse;

                        if (m.Success)
                        {
                            if (!string.IsNullOrEmpty(evaled))
                            {
                                for (int i = 1; i < m.Groups.Count; i++)
                                {
                                    evaled = evaled.Replace("{" + i + "}", m.Groups[i].Value);
                                }
                                ParsedText = ParsedText.Replace(m.Groups[0].Value, evaled);
                            }
                        }
                    }
                }
            }

            string SmileyPat = @":([\w\?\!'-]+):";
            string SmileyFolder = "~/Images/Smilies/";
            Regex SmileyReg = new Regex(SmileyPat, RegexOptions.Compiled);
            MatchCollection smileymatchs = SmileyReg.Matches(ParsedText);

            foreach (Match m in smileymatchs)
            {
                if (m.Success)
                {
                    if (!string.IsNullOrEmpty(Repositories.Smilies.GetSmileyURL(m.Groups[0].Value)))
                    {
                        Smiley thesmiley = Repositories.Smilies.GetSmiley(m.Groups[0].Value);

                        string evaled = thesmiley.ImageURL;
                        if (!string.IsNullOrEmpty(evaled))
                        {
                            TagBuilder imgtag = new TagBuilder("img");
                            imgtag.Attributes.Add("src", Url.Content(SmileyFolder + evaled));
                            imgtag.Attributes.Add("alt", thesmiley.Title);
                            imgtag.Attributes.Add("title", thesmiley.Title);

                            ParsedText = ParsedText.Replace(m.Groups[0].Value, imgtag.ToString());
                        }
                    }
                }
            }

            return ParsedText;
        }

    }
}
